package artid.com.arttogo.app;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.Settings;
import android.support.multidex.MultiDexApplication;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.model.EaseNotifier;
import com.hyphenate.util.EMLog;
import com.iflytek.cloud.SpeechUtility;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import org.xutils.DbManager;
import org.xutils.db.table.TableEntity;
import org.xutils.x;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import artid.com.arttogo.R;
import artid.com.arttogo.activity.ChatActivity;
import artid.com.arttogo.activity.MainActivity;
import artid.com.arttogo.db.SQLHelper;
import artid.com.arttogo.utils.AlertUtils;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;

public class ArtToGoApp extends MultiDexApplication {
    /**
     * Activity列表
     */
    private List<Activity> activityList = new LinkedList<Activity>();
    private List<Activity> mallActivityList = new LinkedList<Activity>();
    private DbManager.DaoConfig config;
    /**
     * 全局唯一实例
     */
    private static ArtToGoApp instance;
    private static Activity activity;
    /**
     * 上下文对象
     */
    private static Context mContext = null;
    /**
     * 环信
     */
    public EaseUI easeUI;
    private EMConnectionListener connectionListener;
    private static String androidId;
    private SQLHelper sqlHelper;
    private LocalBroadcastManager broadcastManager;
    protected EMMessageListener messageListener = null;

    /**
     * 获取类实例对象b
     *
     * @return MyActivityManager
     */
    public static ArtToGoApp getInstance() {
        if (null == instance) {
            instance = new ArtToGoApp();
        }
        return instance;
    }

    /**
     * 关闭保存的Activity
     */
    public void exit() {
        if (activityList != null) {
            Activity activity;
            for (int i = 0; i < activityList.size(); i++) {
                activity = activityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                activityList.remove(i);
                i--;
            }
        }
    }

    /**
     * 获取数据库Helper
     */
    public SQLHelper getSQLHelper() {
        if (sqlHelper == null)
            sqlHelper = new SQLHelper(instance);
        return sqlHelper;
    }

    /**
     * 吧 保存Activity到现有列表中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    public void addMallActivity(Activity activity) {
        mallActivityList.add(activity);
    }
    public void exitMall() {
        if (mallActivityList != null) {
            Activity activity;
            for (int i = 0; i < mallActivityList.size(); i++) {
                activity = mallActivityList.get(i);
                if (activity != null) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }

                    activity = null;
                }
                mallActivityList.remove(i);
                i--;
            }
        }
    }

    public static Context getContext() {
        return mContext;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mContext = getApplicationContext();
        getAndroidId();
        initImageLoader(getApplicationContext());
        // Xutils初始化
        x.Ext.init(this);
        // 是否输出debug日志
        x.Ext.setDebug(true);// 是否输出Debug日志
        // 初始化Xutils数据库
        config = new DbManager.DaoConfig();
        // 每一个config对象描述一个数据库，多个数据库就创建多个config对象
        // 这里作为示例，我们只创建一个名字为dbName版本号为1的数据库
        config.setDbName("catalogueDB").setDbVersion(1);// 设置数据库版本号
        // config.setDbDir(File file);
        // 该语句会将数据库文件保存在你想存储的地方
        // 如果不设置则默认存储在应用程序目录下/database/dbName.db
        config.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                // 用来监听数据库是否升级
                // 如果当前数据库版本号比已存在的数据库版本号高则执行此片段
                // 用途：软件升级之后在第一次运行时执行一些必要的初始化操作
            }
        });
        config.setTableCreateListener(new DbManager.TableCreateListener() {
            @Override
            public void onTableCreated(DbManager db, TableEntity table) {
                // 用来监听数据表的创建
                // 当第一次创建表的时候执行此片段
            }
        });
        config.setAllowTransaction(true);

        // 讯飞语音初始化
        setXunFei();
        mContext = getApplicationContext();
        instance = this;
        // 环信注册

        EMOptions options = new EMOptions();
        options.setAutoLogin(false);
        // 默认添加好友时，是不需要验证的，改成需要验证
        options.setAcceptInvitationAlways(false);
        // 环信小米推送
        options.setMipushConfig(mContext.getResources().getString(R.string.mipushAppid), mContext.getResources().getString(R.string.mipushAppkey));
        if (EaseUI.getInstance().init(mContext, options)) {
            EMClient.getInstance().addConnectionListener(connectionListener);
            EMClient.getInstance().setDebugMode(true);//开启日志
            easeUI = EaseUI.getInstance();
            broadcastManager = LocalBroadcastManager.getInstance(mContext);
            // 调用easeui的api设置providers
            setEaseUIProviders();
            // 注册消息事件监听
            registerEventListener();
            EMClient.getInstance().chatManager().addMessageListener(msgListener);
        }

        // 友盟注册
        //注册推送服务，每次调用register方法都会回调该接口
        PushAgent.getInstance(this).register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.d("log", "友盟ID：" + deviceToken);
                PushAgent.getInstance(mContext).setMessageHandler(mUmengMessageHandler);
                PushAgent.getInstance(mContext).setNotificationClickHandler(notificationClickHandler);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.d("log", "初始化友盟错误：" + s.toString() + "===" + s1.toString());
            }
        });

    }

    /**
     * 讯飞组件初始化
     */
    private void setXunFei() {
        // 应用程序入口处调用，避免手机内存过小，杀死后台进程后通过历史intent进入Activity造成SpeechUtility对象为null
        // 如在Application中调用初始化，需要在Mainifest中注册该Applicaiton
        // 注意：此接口在非主进程调用会返回null对象，如需在非主进程使用语音功能，请增加参数：SpeechConstant.FORCE_LOGIN+"=true"
        // 参数间使用半角“,”分隔。
        // 设置你申请的应用appid,请勿在'='与appid之间添加空格及空转义符
        Log.e("TG", "走了");
        SpeechUtility.createUtility(this, "appid="
                + getString(R.string.xunfei_app_id));
        // 以下语句用于设置日志开关（默认开启），设置成false时关闭语音云SDK日志打印
        // Setting.showLogcat(false);
    }

    public static String getAndroidId() {
        if (TextUtils.isEmpty(androidId)) {
            androidId = Settings.Secure.getString(mContext.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        }
        return androidId;
    }

    public static void setActivity(Activity activity1) {
        activity = activity1;
    }

    public static Activity getActivity() {
        return activity;
    }

    public DbManager.DaoConfig getDaoConfig() {
        return config;
    }

    /**
     * 判断APP是否运行
     *
     * @param MY_PKG_NAME
     * @return
     */
    private boolean APPIsRun(String MY_PKG_NAME) {

        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(MY_PKG_NAME)
                    || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
                isAppRunning = true;
                Log.d("log", info.topActivity.getPackageName()
                        + " info.baseActivity.getPackageName()="
                        + info.baseActivity.getPackageName());
                break;
            }
        }
        return isAppRunning;
    }

    /**
     * 收到环信消息提示框
     */
    public static void showMessageDialog(final Activity mContext,
                                         final EMMessage message) {
        if (AlertUtils.alertDialog != null) {
            AlertUtils.alertDialog.dismiss();
            AlertUtils.alertDialog = null;
        }
        if (isForeground(mContext, "com.aicpsp.artworkarta.ChatActivity") == false) {
            AlertUtils.MessageAlertDialog(
                    mContext,
                    "您有新的询价信息是否进入聊天?",
                    Integer.parseInt(NetUtils.getDisplayMetrics(mContext).get(
                            NetUtils.DM_WIDTH)), new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            switch (v.getId()) {
                                case R.id.tv_ok:
                                    // 确定
                                    // 进入聊天页面
                                    Intent intent = new Intent(mContext, ChatActivity.class);
                                    ChatActivity.message=message;
                                    MainActivity.friendAvatar = message.getStringAttribute("A_head", "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    mContext.startActivity(intent);
                                    AlertUtils.dismiss();
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context
     * @param className 某个界面名称
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }

        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 环信消息接收
     */
    public static EMMessage mEMMessage = null;// 环信消息体
    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onCmdMessageReceived(List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub
            // 透传消息
            Log.d("log", "环信透传消息:" + list_EMMessage.toString());

        }


        @Override
        public void onMessageRead(List<EMMessage> list) {
            // 已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> list) {
            // 已送达
        }

        @Override
        public void onMessageChanged(EMMessage arg0, Object arg1) {
            // TODO Auto-generated method stub
            // 消息状态变动
        }


        @Override
        public void onMessageReceived(List<EMMessage> list_EMMessage) {
            // TODO Auto-generated method stub
            // 收到消息
            MainActivity.isShowMessageDialog = true;
            mEMMessage = list_EMMessage.get(list_EMMessage.size() - 1);
            Intent intent2 = new Intent("com.PersonalActivity.receiver");
            intent2.putExtra("Hxpush", true);
            mContext.sendBroadcast(intent2);
            Intent intent3 = new Intent("com.MainActivity.receiver");
            intent3.putExtra("DotView", true);
            mContext.sendBroadcast(intent3);
        }
    };

    /**
     * 清除ImageLoader缓存
     */
    public static void ClearImageLoaderMemoryClick() {
        ImageLoader.getInstance().clearMemoryCache(); // 清除内存缓存
    }

    public static void initImageLoader(Context context) {
        // ImageLoaderConfiguration configuration =
        // ImageLoaderConfiguration.createDefault(this);//默认配置(开启这个下面的就可以不用设置)
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_menu_rotate) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.ic_menu_rotate) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.ic_menu_rotate) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(false) // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(0) // 下载前的延迟时间
                .cacheInMemory(false) // default 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default 设置下载的图片是否缓存在SD卡中
                .considerExifParams(false) // default
                .imageScaleType(ImageScaleType.EXACTLY) // default
                // 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
                .displayer(new SimpleBitmapDisplayer()) // default
                // 还可以设置圆角图片new RoundedBitmapDisplayer(20)
                .build();
        File cacheDir = StorageUtils.getOwnCacheDirectory(context,
                "imageloader/yjbc/Cache"); // 缓存文件夹路径
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                context)
                .memoryCacheExtraOptions(1024, 800)
                // default = device screen dimensions 内存缓存文件的最大长宽
                .diskCacheExtraOptions(1024, 1024, null)
                // 本地缓存的详细信息(缓存的最大长宽)，最好不要设置这个
                .threadPoolSize(1)
                // default 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO)
                // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(1 * 1024 * 1080))
                // 可以通过自己的内存缓存实现
                .memoryCacheSize(1 * 1024 * 1080)
                // 内存缓存的最大值
                .memoryCacheSizePercentage(1)
                // default
                .diskCacheSize(100 * 1024 * 1080)
                // 50 Mb sd卡(本地)缓存的最大值
                .diskCacheFileCount(100)
                // 可以缓存的文件数量
                // default为使用HASHCODE对UIL进行加密命名， 还可以用MD5(new
                // Md5FileNameGenerator())加密
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .imageDownloader(new BaseImageDownloader(context)) // default
                .imageDecoder(new BaseImageDecoder(true)) // default
                .diskCache(new UnlimitedDiskCache(cacheDir))// 自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                // .writeDebugLogs() // 打印debug log
                .defaultDisplayImageOptions(options).build(); // 开始构建
        ImageLoader.getInstance().init(config);
    }

    /**
     * 摧毁应用进程时候调用
     */
    public void onTerminate() {
        if (sqlHelper != null)
            sqlHelper.close();
        super.onTerminate();
    }

    /**
     * 环信通知栏
     */
    protected void setEaseUIProviders() {
        // 不设置，则使用easeui默认的
        easeUI.getNotifier().setNotificationInfoProvider(
                new EaseNotifier.EaseNotificationInfoProvider() {

                    @Override
                    public String getTitle(EMMessage message) {
                        // 修改标题,这里使用默认
                        return null;
                    }

                    @Override
                    public int getSmallIcon(EMMessage message) {
                        // 设置小图标，这里为默认
                        return 0;
                    }

                    @Override
                    public String getDisplayedText(EMMessage message) {
                        // 设置状态栏的消息提示，可以根据message的类型做相应提示
                        return null;
                    }

                    @Override
                    public String getLatestText(EMMessage message,
                                                int fromUsersNum, int messageNum) {
                        return null;
                        // return fromUsersNum + "个基友，发来了" + messageNum + "条消息";
                    }

                    @Override
                    public Intent getLaunchIntent(EMMessage message) {
                        // 设置点击通知栏跳转事件
                        if (MainActivity.MainActivityisExist == true) {
                            Intent intent = new Intent(mContext,
                                    ChatActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("message", message);
                            intent.putExtras(bundle);
                            MainActivity.friendAvatar = message
                                    .getStringAttribute("A_head",
                                            "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
                            return intent;
                        } else {
                            Intent intent = new Intent(mContext,
                                    MainActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("message", message);
                            intent.putExtras(bundle);
                            intent.putExtra("isHxNotification", true);
                            intent.putExtra("isShowMessageDialog", false);
                            MainActivity.friendAvatar = message
                                    .getStringAttribute("A_head",
                                            "http://172.16.0.3/upload/artPlatform/Addons/Avatar/default_128_128.png");
                            return intent;
                        }
                    }
                });
    }

    protected void registerEventListener() {
        messageListener = new EMMessageListener() {
            private BroadcastReceiver broadCastReceiver = null;

            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d("环信消息", "onMessageReceived id : " + message.getMsgId());
                    // 应用在后台，不需要刷新UI,通知栏提示新消息
                    if (!easeUI.hasForegroundActivies()) {
                        getNotifier().onNewMsg(message);
                    }
                }
            }

            @Override
            public void onCmdMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    EMLog.d("环信消息", "收到透传消息");
                    // 获取消息body
                    EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message
                            .getBody();
                    final String action = cmdMsgBody.action();// 获取自定义action
                    ToastUtil.toast(mContext, "接收到信息：" + messages.toString());
                    Log.d("log", "接收到信息：" + messages.toString());
                    // 获取扩展属性 此处省略
                    // message.getStringAttribute("");
                    EMLog.d("环信消息", String.format("透传消息：action:%s,message:%s",
                            action, message.toString()));
                    final String str = mContext
                            .getString(R.string.receive_the_passthrough);

                    final String CMD_TOAST_BROADCAST = "hyphenate.demo.cmd.toast";
                    IntentFilter cmdFilter = new IntentFilter(
                            CMD_TOAST_BROADCAST);

                    if (broadCastReceiver == null) {
                        broadCastReceiver = new BroadcastReceiver() {
                            @Override
                            public void onReceive(Context context, Intent intent) {
                                // TODO Auto-generated method stub
                                Toast.makeText(mContext,
                                        intent.getStringExtra("cmd_value"),
                                        Toast.LENGTH_SHORT).show();
                            }
                        };

                        // 注册广播接收者
                        mContext.registerReceiver(broadCastReceiver, cmdFilter);
                    }

                    Intent broadcastIntent = new Intent(CMD_TOAST_BROADCAST);
                    broadcastIntent.putExtra("cmd_value", str + action);
                    mContext.sendBroadcast(broadcastIntent, null);
                }
            }

            @Override
            public void onMessageRead(List<EMMessage> list) {

            }

            @Override
            public void onMessageDelivered(List<EMMessage> list) {

            }


            @Override
            public void onMessageChanged(EMMessage message, Object change) {

            }
        };

        EMClient.getInstance().chatManager()
                .addMessageListener(messageListener);
    }

    public EaseNotifier getNotifier() {
        return easeUI.getNotifier();
    }

    /**
     * 友盟消息接收
     */
    UmengMessageHandler mUmengMessageHandler = new UmengMessageHandler() {
        @Override
        public Notification getNotification(Context arg0, UMessage arg1) {
            // TODO Auto-generated method stub
            if (arg1.extra != null) {
                Intent intent0 = new Intent("com.SystemMessage_Fragment.receiver");
                intent0.putExtra("Umpush", true);
                mContext.sendBroadcast(intent0);

                Intent intent2 = new Intent("com.PersonalActivity.receiver");
                intent2.putExtra("Umpush", true);
                mContext.sendBroadcast(intent2);

                Intent intent3 = new Intent("com.MainActivity.receiver");
                intent3.putExtra("DotView", true);
                mContext.sendBroadcast(intent3);
            }

            if (isAppOnForeground(mContext)) {
                PushAgent.getInstance(mContext).setNotificaitonOnForeground(false);
                Intent intent = new Intent("com.BaseActivity.receiver");
                intent.putExtra("isPushToast", true);
                if (arg1.extra != null) {
                    if ("0".equals(arg1.extra.get("messtype"))) {
                        intent.putExtra("PushToast", "您有一个新的系统消息，请去查看！");
                    } else if ("1".equals(arg1.extra.get("messtype"))) {
                        intent.putExtra("PushToast", "您有一个新的回复消息，请去查看！");
                    } else if ("11".equals(arg1.extra.get("messtype"))) {
                        intent.putExtra("PushToast", "您有一个新的专场提醒，请去查看！");
                    } else {
                        intent.putExtra("PushToast", "您有一个推送消息，请去查看！");
                    }
                } else {
                    intent.putExtra("PushToast", "您有一个推送消息，请去查看！");
                }
                mContext.sendBroadcast(intent);
            } else {
                PushAgent.getInstance(mContext).setNotificaitonOnForeground(true);
            }
            return super.getNotification(arg0, arg1);
        }
    };
    /**
     * 友盟通知栏点击事件
     */
    UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
        @Override
        public void dealWithCustomAction(Context context, UMessage msg) {
            Log.d("log", "友盟通知栏：" + msg.extra.toString());
            // 判断系统消息 1为评论回复消息，0为系统消息
            MainActivity.PushMessage = msg.extra;
            //目前都是当前APP在前台时是文字提醒所有直接启动APP
            // 判断App是否已经启动
            /*
            if (APPIsRun("com.aicpsp.artworkartc")) {
				if (!isAppOnForeground(mContext)) {
					// 判断当前APP不再前台
					Intent i = new Intent(mContext, WebViewActivity.class);
					i.putExtra("type", AppUrl.SYSTEMMESSAGE);
					i.putExtra("url", msg.extra.get("messurl"));
					i.putExtra("messageID", msg.extra.get("messid"));
					i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(i);
					mContext.startActivity(i);
				} else {
					Intent intent0 = new Intent("com.MainActivity.receiver");
					intent0.putExtra("PushOnClick", true);
					intent0.putExtra("UmMessageType", msg.extra.get("messtype"));
					intent0.putExtra("UmMessageMessurl",msg.extra.get("messurl"));
					intent0.putExtra("UmMessageID", msg.extra.get("messid"));
					mContext.sendBroadcast(intent0);
				}
			} else {
				startAPP(mContext, "com.aicpsp.artworkartc");
			}
			*/
            startAPP(mContext, "artid.com.arttogo");
        }
    };

    // 在进程中去寻找当前APP的信息，判断是否在前台运行
    public static boolean isAppOnForeground(Context mContext) {
        ActivityManager activityManager = (ActivityManager) mContext
                .getApplicationContext().getSystemService(
                        Context.ACTIVITY_SERVICE);
        String packageName = mContext.getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    /*
     * 启动一个app
     */
    public static void startAPP(Context mContext, String appPackageName) {
        try {
            Intent intent = mContext.getPackageManager()
                    .getLaunchIntentForPackage(appPackageName);
            mContext.startActivity(intent);
        } catch (Exception e) {
            ToastUtil.toast(mContext, "该程序没有安装");
        }
    }
}
